#include "miniqqmusic.h"
#include "ui_miniqqmusic.h"
#include<QPushButton>
#include<QEvent>
#include<QMouseEvent>
#include<QPoint>
#include<QFile>
#include<QDebug>
#include<iostream>
#include<QGraphicsDropShadowEffect>
#include<QJsonObject>
#include<QJsonArray>
#include<QFileDialog>
#include<QMediaPlaylist>
#include<QSqlQuery>
#include<QMessageBox>
#include<QSqlError>
miniqqmusic::miniqqmusic(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::miniqqmusic)
{
    ui->setupUi(this);
    _volumeTool = new VolumeTool(this);//初始化一个音量控件
    this->InitUI();
    InitSql();
    InitMusicList();
    mediaInit();

}

miniqqmusic::~miniqqmusic()
{
    delete ui;
}

void miniqqmusic::InitUI()
{
    this->setWindowIcon(QIcon(":/image/tubiao.png"));
    //创建lrc对象；
    ui->max->setEnabled(false);//禁止最大窗口的显示；
    _lrcPage = new LrcPage(this);
    _lrcPage->hide();

    _aniation = new QPropertyAnimation(_lrcPage,"geometry",this);


    this->setWindowFlag(Qt::WindowType::FramelessWindowHint);//取消窗口自带的最大最小化；
    connect(ui->quit,&QPushButton::clicked,this,&miniqqmusic::Quit);
//    this->setAttribute(Qt::WA_TranslucentBackground);

//     // 给窗⼝设置阴影效果
//     QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(this);
//     shadowEffect->setOffset(0,0); // 设置阴影偏移
//     shadowEffect->setColor("#000000"); // 设置阴影颜⾊：⿊⾊
//     shadowEffect->setBlurRadius(10); // 设置阴影的模糊半径
//     this->setGraphicsEffect(shadowEffect);
     this->myPushButtonInit();
     connectSignalandSolit();
//     randomPixmap();
     srand(time(nullptr));
    ui->recMusicBox->initRecBoxUI(randomPixmap(),1);
    ui->suplayMusicBox->initRecBoxUI(randomPixmap(),2);
    ui->likePage->setCommonUI("我喜欢",":/image/ilikebg.png");
    ui->likePage->setPageType(PageType::LIKE_PAGE);
    ui->localPage->setPageType(PageType::LOCK_PAGE);
    ui->recentPage->setPageType(PageType::HISTORY_PAGE);
    ui->localPage->setCommonUI("本地下载",":/image/localbg.png");
    ui->recentPage->setCommonUI("最近",":/image/recentbg.png");
    ui->play->setIcon(QIcon(":/image/play_2.png"));
    ui->playMode->setIcon(QIcon(":/image/list_play.png"));
    ui->playMode->setToolTip("循环播放");

    _currentPage = ui->localPage;//默认localpage页面；
}

void miniqqmusic::Quit()
{
    //进行数据库的插入；
    _musicList.writeToDB();
//    QSqlQuery query("DROP TABLE IF EXISTS musicInfo");
//    if(!query.exec())
//    {
//        qDebug()<<"delet err"<<query.lastError().text();
//    }
    _sql.close();
    close();
}

void miniqqmusic::myPushButtonInit()
{
    //自定义按钮初始化；
    ui->rec->setIcon(":/image/rec.png","推荐",0);
    ui->music->setIcon(":/image/music.png","音乐馆",2);
    ui->radio->setIcon(":/image/radio.png","电台",1);
    ui->like->setIcon(":/image/like.png","喜欢",3);
    ui->local->setIcon(":/image/local.png","本地",4);
    ui->recent->setIcon(":/image/recent.png","最近",5);
    ui->local->getPropertyAnimation();
    ui->stackedWidget->setCurrentIndex(4);//设置默认界面为本地音乐；
}

void miniqqmusic::connectSignalandSolit()
{
    connect(ui->rec,&BtForm::btCliced,this,&miniqqmusic::onBtFormCliced);
    connect(ui->radio,&BtForm::btCliced,this,&miniqqmusic::onBtFormCliced);
    connect(ui->music,&BtForm::btCliced,this,&miniqqmusic::onBtFormCliced);
    connect(ui->like,&BtForm::btCliced,this,&miniqqmusic::onBtFormCliced);
    connect(ui->local,&BtForm::btCliced,this,&miniqqmusic::onBtFormCliced);
    connect(ui->recent,&BtForm::btCliced,this,&miniqqmusic::onBtFormCliced);
    connect(ui->localPage,&CommonPage::updateLikePage,this,&miniqqmusic::updateLikePageHandler);
    connect(ui->likePage,&CommonPage::updateLikePage,this,&miniqqmusic::updateLikePageHandler);
    connect(ui->recentPage,&CommonPage::updateLikePage,this,&miniqqmusic::updateLikePageHandler);
    connect(ui->likePage,&CommonPage::playAll,this,&miniqqmusic::playAllHandler);
    connect(ui->localPage,&CommonPage::playAll,this,&miniqqmusic::playAllHandler);
    connect(ui->recentPage,&CommonPage::playAll,this,&miniqqmusic::playAllHandler);

    connect(ui->likePage,&CommonPage::playMusicIndex,this,&miniqqmusic::playIndexHandler);
    connect(ui->localPage,&CommonPage::playMusicIndex,this,&miniqqmusic::playIndexHandler);
    connect(ui->recentPage,&CommonPage::playMusicIndex,this,&miniqqmusic::playIndexHandler);

    connect(_volumeTool,&VolumeTool::muteChanged,this,[=](bool isMute)
    {
       _mediaPlayer->setMuted(isMute);
    });

    connect(_volumeTool,&VolumeTool::volumeChanged,this,&miniqqmusic::setVolume);

    connect(ui->processBar,&MusicSlider::processBarPosition,this,&miniqqmusic::positionByProcessBar);
}

QJsonArray miniqqmusic::randomPixmap()
{
    QVector<QString>vImageName;
    QJsonArray jsArry;
    vImageName<<"001.png"<<"003.png"<<"004.png"<<"005.png"<<"006.png"<<"007.png"
             <<"008.png"<<"009.png"<<"010.png"<<"011.png"<<"012.png"<<"013.png"<<"014.png"
               <<"015.png"<<"016.png"<<"017.png"<<"018.png"<<"019.png"<<"020.png"<<"021.png"<<"022.png"<<"023.png"
                 <<"024.png"<<"025.png"<<"026.png"<<"027.png"<<"028.png"<<"029.png"<<"030.png"<<"031.png"<<"032.png"
                   <<"033.png"<<"034.png"<<"035.png"<<"036.png"<<"037.png"<<"038.png"<<"039.png"<<"040.png";
   std::random_shuffle(vImageName.begin(),vImageName.end());//random
   int i = 0;
   for(auto e:vImageName)
   {
       QJsonObject obj;
       obj.insert("path",":/image/rec/"+e);
       QString text = QString("推荐-%1").arg(i,3,10,QChar('0'));
       obj.insert("text",text);
       jsArry.append(obj);
       i++;
   }
   return jsArry;
}

void miniqqmusic::mediaInit()
{
    _mediaPlayer = new QMediaPlayer(this);
    _playList = new QMediaPlaylist(this);
    //设置播放模式
    _playList->setPlaybackMode(QMediaPlaylist::Loop);//这个模式必须要是loop不可以是currentloop
    //将播放列表添加到媒体中；
    _mediaPlayer->setPlaylist(_playList);

    //设置播放音量；
    _mediaPlayer->setVolume(20);
    connect(_playList,&QMediaPlaylist::playbackModeChanged,this,&miniqqmusic::setPlaylistModeIcon);
    connect(_mediaPlayer,&QMediaPlayer::stateChanged,this,&miniqqmusic::changeModeIcon);
    connect(_playList,&QMediaPlaylist::currentIndexChanged,this,&miniqqmusic::currentIndexChanged);

    connect(_mediaPlayer,&QMediaPlayer::durationChanged,this,&miniqqmusic::durationHandler);

    connect(_mediaPlayer,&QMediaPlayer::positionChanged,this,&miniqqmusic::positionHandler);

    //当前播放改变时，需要修改歌名；
    connect(_mediaPlayer,&QMediaPlayer::currentMediaChanged,this,&miniqqmusic::setBaseImage);

}

void miniqqmusic::playMusicByIndex(CommonPage *page,int index)
{
    //播放指定页面哪一个音乐；
    _playList->clear();
    _currentPage = page;
    page->addMusicToPlaylist(_musicList,_playList);
    _playList->setCurrentIndex(index);
    _mediaPlayer->play();
}

void miniqqmusic::InitSql()
{
    //初始化数据库；
    //建立连接；
    _sql = QSqlDatabase::addDatabase("QSQLITE");
    //创建数据库；
    _sql.setDatabaseName("MiniQQMusic.db");
    //打开数据库；
    if(!_sql.open())
    {
        //没有打开成功，弹出一个QMessage的窗口；
       QMessageBox::critical(this,"打开数据库失败","");
       return;
    }
    qDebug()<<"SQLite连接成功，并创建 [MiniQQMusic.db] 数据库!!!";
    //创建表；
    //需要QSqlQuery;
    QString sql = ("CREATE TABLE IF NOT EXISTS musicInfo(\
     id INTEGER PRIMARY KEY AUTOINCREMENT,\
     musicId varchar(200) UNIQUE,\
     musicName varchar(50),\
     musicSinger varchar(50),\
     albumName varchar(50),\
     duration BIGINT,\
     musicUrl varchar(256),\
     isLike INTEGER,\
     isHistory INTEGER)"
     );
    QSqlQuery query(sql);
    if(!query.exec())
    {
        //创建表失败；
        QMessageBox::critical(this,"创建数据库表失败","");
        return;
    }
    qDebug()<<"create table success";

}

void miniqqmusic::InitMusicList()
{
    //读取数据库信息，加载页面信息；
    _musicList.readFormDB();
    ui->likePage->reFresh(_musicList);
    ui->localPage->reFresh(_musicList);
    ui->recentPage->reFresh(_musicList);
}
void miniqqmusic::mouseMoveEvent(QMouseEvent *event)
{
    //处理鼠标移动事件；
    //buttons()用于描述一直按着的键
    if(event->buttons() == Qt::LeftButton)
    {
        this->move(event->globalPos() - this->point);
        return;
     }
    QWidget::mouseMoveEvent(event);
}
void miniqqmusic::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        this->point = event->globalPos() - this->frameGeometry().topLeft();
        return;
    }
    QWidget::mousePressEvent(event);
}

void miniqqmusic::onBtFormCliced(int index)
{
//    qDebug()<<"index"<<index<<endl;
    QList<BtForm*>btformlist = this->findChildren<BtForm*>();//获取界面所有的自定义按钮；
    for(auto bt:btformlist)
    {
        if(bt->getIndex()!=index)
        {
            bt->cleanBtForm();
        }
    }
    ui->stackedWidget->setCurrentIndex(index);
    //    qDebug()<<"当前的page:"<<index<<endl;
}

void miniqqmusic::updateLikePageHandler(const QString &musicId)
{
    //直接更新页面信息；
    ui->localPage->reFresh(_musicList);
    ui->likePage->reFresh(_musicList);
    ui->recentPage->reFresh(_musicList);
    (void)musicId;
}


void miniqqmusic::on_volume_clicked()
{
    //设置起始坐标；
    QPoint point = ui->volume->mapToGlobal(QPoint(0,0));//获取volume全局坐标；
    //获取volumeTool移动坐标；
    QPoint volumePoint = point - QPoint(_volumeTool->width()/2 ,_volumeTool->height());
    volumePoint.setX(volumePoint.x() + 15);
    volumePoint.setY(volumePoint.y() + 10);
    _volumeTool->move(volumePoint);
    _volumeTool->show();
}

void miniqqmusic::on_addLocal_clicked()
{
    //创建filedialog对象；
   QFileDialog filedialog;
   //默认是一打开的方式创建
   QDir dir(QDir::currentPath());
   dir.cdUp();
   QString path = dir.path() + "/MiniQQMusic";
   filedialog.setDirectory(path);
   filedialog.setWindowTitle("添加本地音乐");
   filedialog.setAcceptMode(QFileDialog::AcceptOpen);//一打开的方式；
   filedialog.setFileMode(QFileDialog::ExistingFiles);//可以一次性打开多个文件；
//   filedialog.setNameFilter("*.cpp *.h");
   if(QFileDialog::Accepted == filedialog.exec())
   {
       //获取URL；
       qDebug()<<"打开成功"<<endl;
       QList<QUrl>urls = filedialog.selectedUrls();
       _musicList = MusicList(urls);
       ui->stackedWidget->setCurrentIndex(4);
       ui->localPage->reFresh(_musicList);
       //当获取了音乐链表的时候，就可以进行播放链表的更新了
       ui->localPage->addMusicToPlaylist(_musicList,_playList);

   }
}

void miniqqmusic::on_play_clicked()
{
    //当点击的是候，播放音乐和停止；
    if(_mediaPlayer->state() == QMediaPlayer::StoppedState)
    {
        //第一次点击的时候，启动播放；
        _mediaPlayer->play();
    }
    else if(_mediaPlayer->state() == QMediaPlayer::PlayingState)
    {
        //正在播放，点击暂停；
        _mediaPlayer->pause();

    }
    else
    {
        //点击播放；
        _mediaPlayer->play();

    }
}

void miniqqmusic::on_playUp_clicked()
{
    //播放上一首音乐；
    _playList->previous();
    qDebug()<<_playList->mediaCount();
}

void miniqqmusic::on_playDown_clicked()
{
    //播放下一首音乐；
    _playList->next();
    qDebug()<<"down";
}

void miniqqmusic::on_playMode_clicked()
{
    //控制播放模式；
    if(_playList->playbackMode() == QMediaPlaylist::Loop)
    {
        //变成列表播放；
        _playList->setPlaybackMode(QMediaPlaylist::Random);
        //设置tooltip
        ui->playMode->setToolTip("随机播放");
    }
    else if(_playList->playbackMode() == QMediaPlaylist::Random)
    {
        //设置为单曲循环；
        _playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
        ui->playMode->setToolTip("单曲循环");
    }
    else if(_playList->playbackMode() == QMediaPlaylist::CurrentItemInLoop)
    {
        //设置为循环播放；
        _playList->setPlaybackMode(QMediaPlaylist::Loop);
        ui->playMode->setToolTip("循环播放");
    }
    else
    {
        qDebug()<<"其他暂不支持";
    }
}

void miniqqmusic::setPlaylistModeIcon(QMediaPlaylist::PlaybackMode playMdoe)
{
    //通过信号playbackModeChanged;
    if(playMdoe == QMediaPlaylist::Loop)
    {
        ui->playMode->setIcon(QIcon(":/image/list_play.png"));
    }
    else if(playMdoe == QMediaPlaylist::Random)
    {
        ui->playMode->setIcon(QIcon(":/image/shuffle_2.png"));
    }
    else if(playMdoe == QMediaPlaylist::CurrentItemInLoop)
    {
        ui->playMode->setIcon(QIcon(":/image/single_play.png"));
    }
    else
    {
        qDebug()<<"暂不支持";
    }
}

void miniqqmusic::playAllHandler(PageType pageType)
{

    //判断当前是哪个页面；
    CommonPage*page = nullptr;
    if(pageType == PageType::LIKE_PAGE)
    {
        page = ui->likePage;
    }
    else if(pageType == PageType::LOCK_PAGE)
    {
        page = ui->localPage;
    }
    else if(pageType == PageType::HISTORY_PAGE)
    {
        page = ui->recentPage;
    }
    else
    {
        qDebug()<<"暂不支持";
    }
    _currentPage = page;
    playMusicByIndex(page,0);
}

void miniqqmusic::playIndexHandler(CommonPage *page, int index)
{

    this->playMusicByIndex(page,index);
}

void miniqqmusic::changeModeIcon(QMediaPlayer::State state)
{
    //当播放状态改变的时候，_mediaPlay会发射信号；
    if(state == QMediaPlayer::PlayingState)
    {
        ui->play->setIcon(QIcon(":/image/play_on.png"));
    }
    else if(state == QMediaPlayer::StoppedState)
    {
        ui->play->setIcon(QIcon(":/image/play_2.png"));
    }
    else if(state == QMediaPlayer::PausedState)
    {
        ui->play->setIcon(QIcon(":/image/play_2.png"));
    }
}

void miniqqmusic::currentIndexChanged(int index)
{
     _currentIndex = index;//当前播放的下标；
    //当_playlist当前播放改变是发射信号；
    QString musicId = _currentPage->getMusicId(index);
    auto it = _musicList.findId(musicId);
    if(it != _musicList.end())
    {
        it->setIsHistory(true);
    }
    ui->recentPage->reFresh(_musicList);

}

void miniqqmusic::setVolume(int volume)
{
    _mediaPlayer->setVolume(volume);
}

void miniqqmusic::durationHandler(qint64 duration)
{
    qint64 minute = duration/1000/60;
    qint64 secend = duration/1000%60;
    ui->totalTime->setText(QString("%1:%2").arg(minute,2,10,QChar('0'))
                           .arg(secend,2,10,QChar('0')));
}

void miniqqmusic::positionHandler(qint64 position)
{
    qint64 minute = position/1000/60;
    qint64 secend = position/1000%60;
    ui->curentTime->setText(QString("%1:%2").arg(minute,2,10,QChar('0'))
                            .arg(secend,2,10,QChar('0')));
    //在时间变化的时候，需要更新processBar的进度条；
    ui->processBar->setProcessBarByTime(position/(double)_mediaPlayer->duration());

    //在当前歌曲时间变化时，更新歌词页面；
    _lrcPage->showLrcWord(position);
}

void miniqqmusic::positionByProcessBar(double ration)
{
    qint64 position = ration*_mediaPlayer->duration();
    qint64 minute = position/1000/60;
    qint64 secend = position/1000%60;
    ui->curentTime->setText(QString("%1:%2").arg(minute,2,10,QChar('0'))
                            .arg(secend,2,10,QChar('0')));
    _mediaPlayer->setPosition(position);
}

void miniqqmusic::setBaseImage(QMediaContent content)
{
    //获取当前播放的music对象；
    QString musicId = _currentPage->getMusicId(_currentIndex);
    auto it = _musicList.findId(musicId);
    QString musicName("未知音乐");
    QString musicSinger("未知歌手");
    if(it != _musicList.end())
    {
        musicName = it->getMusicName();
        musicSinger = it->getMusicSinger();
    }
    ui->musicName->setText(musicName);
    ui->musicSigner->setText(musicSinger);
    if(it != _musicList.end())
    {
        //获取lrc路径；
        QString path = it->getLrcFilePath();
        _lrcPage->parseLrc(path);
    }
    // 3. 获取封⾯图⽚
     QVariant coverImage = _mediaPlayer->metaData("ThumbnailImage");
     if(coverImage.isValid())
     {
     // 获取封⾯图⽚成功
     QImage image = coverImage.value<QImage>();
     // 设置封⾯图⽚
     ui->musicCover->setPixmap(QPixmap::fromImage(image));
     // 缩放填充到整个Label
     _currentPage->setCurrentImage(QPixmap::fromImage(image));
     }
     else
     {
     // 设置默认图⽚-修改
         ui->musicCover->setPixmap(QPixmap(":/image/rec/001.png"));
         _currentPage->setCurrentImage(QPixmap(":/image/rec/001.png"));
     qDebug()<<"歌曲没有封⾯图⽚";
     }
      ui->musicCover->setScaledContents(true);
    (void)content;
}

void miniqqmusic::on_lrcWord_clicked()
{
    //显示lrcpage页面；
    _lrcPage->show();
    _aniation->setDuration(250);
    _aniation->setStartValue(QRect(0,width(),width(),height()));
    _aniation->setEndValue(QRect(0,0,width(),height()));
    _aniation->start();
}

void miniqqmusic::on_min_clicked()
{
    showMinimized();
}

void miniqqmusic::on_skin_clicked()
{
    QMessageBox::critical(this,"温馨提示","更换皮肤效果还在更新中");
}
